import 'dart:math';

import '../shared/models/word.dart';
import 'esperanto_vocabulary_large.dart';
import 'esperanto_vocabulary_extended.dart';
import 'esperanto_roots_affixes.dart';
import 'esperanto_advanced_vocabulary.dart';
import 'esperanto_mega_vocabulary.dart';
import 'esperanto_vocabulary_batch2.dart';
import 'esperanto_vocabulary_batch3.dart';
import 'esperanto_vocabulary_batch4.dart';
import 'esperanto_vocabulary_batch5.dart';
import 'esperanto_vocabulary_batch6.dart';
import 'esperanto_vocabulary_batch7.dart';
import 'esperanto_vocabulary_batch8.dart';
import 'esperanto_vocabulary_batch9.dart';
import 'esperanto_vocabulary_supplement.dart';

class MasterVocabulary {
  // 所有词汇类别
  static const Map<String, String> categoryDescriptions = {
    // 基础词汇
    'Animals': '动物类 - 各种动物的世界语词汇',
    'Plants': '植物类 - 花草树木相关词汇',
    'Food': '食物类 - 饮食相关词汇',
    'Numbers': '数字类 - 数字和序数词',
    
    // 扩展词汇
    'Colors': '颜色类 - 各种颜色的表达',
    'Body Parts': '身体部位 - 人体各部位名称',
    'Clothing': '服装类 - 衣物和配饰',
    'Household': '家居用品 - 家庭日用物品',
    'Transportation': '交通工具 - 各种交通方式',
    
    // 高级词汇
    'Time': '时间类 - 时间相关词汇',
    'Weather': '天气类 - 天气和自然现象',
    
    // 专业词汇
    'Medical': '医学类 - 健康医疗相关词汇',
    'Arts': '艺术类 - 艺术文化相关词汇',
    'Professions': '职业类 - 各种职业和工作',
    'Education': '教育类 - 学习教育相关词汇',
    
    // 词根词缀
    'Roots': '词根 - 世界语基础词根',
    'Basic Roots': '基础词根 - 世界语核心词根',
    'Professional Roots': '专业词根 - 专业领域词根',
    'Compound Roots': '复合词根 - 复合概念词根',
    'Scientific Roots': '科学词根 - 科学技术词根',
    'Prefixes': '前缀 - 常用前缀词缀',
    'Suffixes': '后缀 - 语法和词汇后缀',
    'Advanced Prefixes': '高级前缀 - 复杂前缀词缀',
    'Advanced Suffixes': '高级后缀 - 复杂后缀词缀',
    'Functional Suffixes': '功能后缀 - 功能性后缀词缀',
  };

  // 难度等级描述
  static const Map<int, String> difficultyDescriptions = {
    1: '初级 - 基础日常词汇',
    2: '中级 - 常用进阶词汇',
    3: '高级 - 复杂专业词汇',
  };

  // 获取所有词汇
  static List<Word> get allVocabulary => [
    ...EsperantoVocabularyLarge.allVocabulary,
    ...EsperantoVocabularyExtended.allExtendedVocabulary,
    ...EsperantoAdvancedVocabulary.allAdvancedVocabulary,
    ...EsperantoRootsAffixes.allRootsAffixes,
    ...EsperantoMegaVocabulary.getAllWords(),
    ...EsperantoVocabularyBatch2.getAllWords(),
    ...EsperantoVocabularyBatch3.getAllWords(),
    ...EsperantoVocabularyBatch4.getAllWords(),
    ...EsperantoVocabularyBatch5.getAllWords(),
    ...EsperantoVocabularyBatch6.getAllWords(),
    ...EsperantoVocabularyBatch7.getAllWords(),
    ...EsperantoVocabularyBatch8.getAllWords(),
    // 第九批次 - 基于用户列表的重要词根
    ...EsperantoVocabularyBatch9.getAllWords(),
    // 补充词汇 - 达到1000词汇目标
    ...EsperantoVocabularySupplement.getAllWords(),
  ];

  // 根据类别获取词汇
  static List<Word> getWordsByCategory(String category) {
    return allVocabulary.where((word) => word.category == category).toList();
  }

  // 根据难度获取词汇
  static List<Word> getWordsByDifficulty(int difficulty) {
    return allVocabulary.where((word) => word.difficulty == difficulty).toList();
  }

  // 根据类别和难度获取词汇
  static List<Word> getWordsByCategoryAndDifficulty(String category, int difficulty) {
    final categoryWords = getWordsByCategory(category);
    return categoryWords.where((word) => word.difficulty == difficulty).toList();
  }

  // 获取随机词汇
  static List<Word> getRandomWords(int count, {String? category, int? difficulty}) {
    List<Word> wordPool;
    
    if (category != null && difficulty != null) {
      wordPool = getWordsByCategoryAndDifficulty(category, difficulty);
    } else if (category != null) {
      wordPool = getWordsByCategory(category);
    } else if (difficulty != null) {
      wordPool = getWordsByDifficulty(difficulty);
    } else {
      wordPool = allVocabulary;
    }
    
    final shuffled = List<Word>.from(wordPool)..shuffle();
    return shuffled.take(count).toList();
  }

  // 获取所有类别
  static List<String> getAllCategories() {
    final allCategories = <String>{};
    allCategories.addAll(EsperantoVocabularyLarge.getAllCategories());
    allCategories.addAll(EsperantoVocabularyExtended.getAllCategories());
    allCategories.addAll(EsperantoAdvancedVocabulary.getAllCategories());
    allCategories.addAll(EsperantoRootsAffixes.getAllCategories());
    allCategories.addAll(EsperantoMegaVocabulary.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch2.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch3.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch4.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch5.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch6.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch7.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch8.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularyBatch9.getAllWords().map((w) => w.category));
    allCategories.addAll(EsperantoVocabularySupplement.getAllWords().map((w) => w.category));
    return allCategories.toList()..sort();
  }

  // 获取基础类别（适合初学者）
  static List<String> getBasicCategories() {
    return EsperantoVocabularyLarge.getAllCategories();
  }

  // 获取扩展类别（适合进阶学习）
  static List<String> getExtendedCategories() {
    return [
      ...EsperantoVocabularyExtended.getAllCategories(),
      ...EsperantoAdvancedVocabulary.getAllCategories(),
    ];
  }

  // 获取词根词缀类别（适合深度学习）
  static List<String> getRootsAffixesCategories() {
    return EsperantoRootsAffixes.getAllCategories();
  }

  // 获取类别统计信息
  static Map<String, int> getCategoryStats() {
    final stats = <String, int>{};
    for (final category in getAllCategories()) {
      stats[category] = getWordsByCategory(category).length;
    }
    return stats;
  }

  // 获取难度统计信息
  static Map<int, int> getDifficultyStats() {
    final stats = <int, int>{};
    for (int difficulty = 1; difficulty <= 3; difficulty++) {
      stats[difficulty] = getWordsByDifficulty(difficulty).length;
    }
    return stats;
  }

  // 搜索词汇
  static List<Word> searchWords(String query) {
    final lowerQuery = query.toLowerCase();
    return allVocabulary.where((word) {
      return word.esperanto.toLowerCase().contains(lowerQuery) ||
             word.english.toLowerCase().contains(lowerQuery) ||
             word.definition.toLowerCase().contains(lowerQuery) ||
             word.examples.any((example) => example.toLowerCase().contains(lowerQuery));
    }).toList();
  }

  // 获取推荐学习序列（按难度递增）
  static List<String> getRecommendedLearningSequence() {
    return [
      // 基础词汇（难度1）
      'Numbers',
      'Colors',
      'Animals',
      'Food',
      'Body Parts',
      'Household',
      
      // 进阶词汇（难度1-2）
      'Plants',
      'Clothing',
      'Transportation',
      
      // 语法基础（难度1-2）
      'Suffixes',
      
      // 词汇构造（难度2-3）
      'Prefixes',
      'Roots',
    ];
  }

  // 获取每日推荐词汇（基于日期的伪随机）
  static List<Word> getDailyWords({int count = 10}) {
    final today = DateTime.now();
    final seed = today.year * 10000 + today.month * 100 + today.day;
    final random = Random(seed);
    
    final shuffled = List<Word>.from(allVocabulary);
    shuffled.shuffle(random);
    
    return shuffled.take(count).toList();
  }

  // 获取词汇总数
  static int get totalWordCount => allVocabulary.length;

  // 获取类别描述
  static String getCategoryDescription(String category) {
    return categoryDescriptions[category] ?? '未知类别';
  }

  // 获取难度描述
  static String getDifficultyDescription(int difficulty) {
    return difficultyDescriptions[difficulty] ?? '未知难度';
  }

  // 验证数据完整性
  static Map<String, dynamic> validateData() {
    final issues = <String>[];
    final stats = <String, dynamic>{};
    
    // 检查重复ID
    final ids = allVocabulary.map((w) => w.id).toList();
    final uniqueIds = ids.toSet();
    if (ids.length != uniqueIds.length) {
      issues.add('发现重复的词汇ID');
    }
    
    // 检查空字段
    for (final word in allVocabulary) {
      if (word.esperanto.isEmpty) issues.add('发现空的世界语字段: ${word.id}');
      if (word.english.isEmpty) issues.add('发现空的英语字段: ${word.id}');
      if (word.pronunciation.isEmpty) issues.add('发现空的发音字段: ${word.id}');
      if (word.definition.isEmpty) issues.add('发现空的定义字段: ${word.id}');
      if (word.examples.isEmpty) issues.add('发现空的例句字段: ${word.id}');
    }
    
    stats['totalWords'] = totalWordCount;
    stats['categories'] = getAllCategories().length;
    stats['issues'] = issues;
    stats['categoryStats'] = getCategoryStats();
    stats['difficultyStats'] = getDifficultyStats();
    
    return stats;
  }
}

 